package logic

import (
	"context"
	"errors"

	"test-api/internal/model"
	"test-api/internal/svc"
	"test-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type UserUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserUpdateLogic) UserUpdate(req *types.STUserUpdateReq) (resp *types.STUserUpdateRsp, err error) {
	resp = &types.STUserUpdateRsp{}

	v := &model.User{}
	db := l.svcCtx.DB.Model(&v).Where("id=?", req.Id).Where("state = 1")

	if err = db.First(&v).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return resp, errors.New("数据不存在")
		}
		return resp, errors.New("数据库错误")
	}

	if err = db.Updates(&model.User{
		Name:   req.Name,
		Mobile: req.Mobile,
	}).Error; err != nil {
		return resp, errors.New("数据库错误")
	}

	return resp, nil
}
